-- EnemyAI.lua (增强版)
-- 敌人AI系统 - 提升攻击性，添加状态追踪

local Vector2 = require("vector")

local EnemyAI = {}
EnemyAI.__index = EnemyAI

function EnemyAI.new(enemyType, enemyData, playerEntity, enemyMovementSystem)
    local instance = setmetatable({
        enemyType = enemyType,
        enemyData = enemyData,
        playerEntity = playerEntity,
        enemyMovementSystem = enemyMovementSystem,
        
        -- AI状态
        state = "idle",  -- idle, patrol, chase, attack, retreat
        aiTimer = 0,
        decisionInterval = 0.3,  -- AI决策间隔缩短，提升响应速度
        
        -- 巡逻相关
        patrolDirection = 1,  -- 1:右, -1:左
        patrolRange = 200,    -- 巡逻范围
        originalX = enemyData.position.x,
        idleTimer = 0,        -- 空闲计时器
        maxIdleTime = 2.0,    -- 最大空闲时间
        
        -- 战斗相关
        attackRange = {
            sword = 100,      -- 剑士近战范围
            archer = 400,     -- 弓箭手射击范围
            broadsword = 120, -- 刀兵攻击范围
            boss = 150        -- Boss攻击范围
        },
        chaseRange = 800,     -- 增加追击范围
        sightRange = 1000,    -- 增加视野范围
        
        -- 攻击冷却
        attackCooldown = 0,
        attackCooldownTime = {
            sword = 1.2,      -- 缩短攻击冷却
            archer = 1.5,
            broadsword = 1.8,
            boss = 0.8
        },
        
        -- 平台边界检测
        platformLeft = nil,
        platformRight = nil,
        currentPlatform = nil,
        
        -- 攻击性参数
        aggressionLevel = 1.0,  -- 攻击性等级
        lastAttackTime = 0,     -- 上次攻击时间
        attackFrequency = 2.0,  -- 攻击频率（每秒攻击次数）
        
        -- 特定敌人状态
        isCharging = false,      -- 刀兵举刀状态
        isDashing = false,       -- 剑士冲锋状态
        dashCooldown = 0,        -- 冲锋冷却
        dashDistance = 0,        -- 冲锋距离
        isSkillCombo = false,    -- 刀兵连斩状态
        
        -- 弓箭手特定
        arrowCooldown = 0,       -- 箭矢冷却
        
        -- 状态追踪
        lastPlayerPosition = nil,
        playerPositionHistory = {},
        predictionTime = 0.3,    -- 玩家位置预测时间
        
        -- Boss专用
        isBossJumpAttacking = false,
        bossJumpCooldown = 0,
        
        -- 调试模式
        debugMode = true,
        frameCount = 0
    }, EnemyAI)
    
    -- 检测当前平台边界
    instance:detectPlatformBoundaries()
    
    return instance
end

-- 检测平台边界
function EnemyAI:detectPlatformBoundaries()
    if not self.enemyMovementSystem or not self.enemyData then return end
    
    local enemyX = self.enemyData.position.x
    local enemyY = self.enemyData.position.y
    local radius = self.enemyData.radius or 20
    
    -- 获取所有地面平台
    local groundPlatforms = self.enemyMovementSystem.groundPlatforms or {}
    
    for _, platform in ipairs(groundPlatforms) do
        -- 检查敌人是否在这个平台上
        if enemyX >= platform.x and enemyX <= platform.x + platform.width then
            local platformTop = platform.y + platform.height
            local enemyBottom = enemyY - radius
            
            -- 敌人站在平台上
            if math.abs(enemyBottom - platformTop) < 10 then
                self.currentPlatform = platform
                self.platformLeft = platform.x + radius
                self.platformRight = platform.x + platform.width - radius
                
                if self.debugMode then
                    print(string.format("敌人检测到平台: 左边界=%.1f, 右边界=%.1f", 
                        self.platformLeft, self.platformRight))
                end
                break
            end
        end
    end
end

-- 检查是否能看到玩家
function EnemyAI:canSeePlayer()
    if not self.playerEntity then return false end
    
    local enemyPos = self.enemyData.position
    local playerPos = self.playerEntity.position
    
    -- 计算距离
    local distanceX = math.abs(playerPos.x - enemyPos.x)
    local distanceY = math.abs(playerPos.y - enemyPos.y)
    
    -- 检查是否在视野范围内
    if distanceX > self.sightRange or distanceY > 300 then
        return false
    end
    
    -- 检查是否在同一平台（Y轴相近）
    if distanceY > 150 then  -- 稍微放宽Y轴限制
        return false
    end
    
    -- 记录玩家位置用于预测
    if not self.lastPlayerPosition then
        self.lastPlayerPosition = {x = playerPos.x, y = playerPos.y}
    else
        table.insert(self.playerPositionHistory, {
            x = playerPos.x,
            y = playerPos.y,
            time = os.time()
        })
        
        -- 保持历史记录不超过10条
        if #self.playerPositionHistory > 10 then
            table.remove(self.playerPositionHistory, 1)
        end
    end
    
    return true
end

-- 预测玩家位置
function EnemyAI:predictPlayerPosition()
    if #self.playerPositionHistory < 2 then
        return self.playerEntity.position
    end
    
    local lastPos = self.playerPositionHistory[#self.playerPositionHistory]
    local secondLastPos = self.playerPositionHistory[#self.playerPositionHistory - 1]
    
    -- 计算速度
    local velocityX = lastPos.x - secondLastPos.x
    local velocityY = lastPos.y - secondLastPos.y
    
    -- 预测位置
    local predictedPos = {
        x = lastPos.x + velocityX * self.predictionTime,
        y = lastPos.y + velocityY * self.predictionTime
    }
    
    return predictedPos
end

-- 检查玩家是否在攻击范围内
function EnemyAI:isPlayerInAttackRange()
    if not self.playerEntity then return false end
    
    local enemyPos = self.enemyData.position
    local playerPos = self:predictPlayerPosition()
    
    local distanceX = math.abs(playerPos.x - enemyPos.x)
    local distanceY = math.abs(playerPos.y - enemyPos.y)
    
    local attackRange = self.attackRange[self.enemyType] or 100
    
    return distanceX <= attackRange and distanceY <= 80  -- 稍微放宽Y轴限制
end

-- 检查玩家是否在同一平台
function EnemyAI:isPlayerOnSamePlatform()
    if not self.playerEntity then return false end
    
    local enemyPos = self.enemyData.position
    local playerPos = self.playerEntity.position
    
    local distanceY = math.abs(playerPos.y - enemyPos.y)
    
    return distanceY <= 80  -- 放宽同一平台判断
end

-- 限制在平台范围内
function EnemyAI:clampToPlatform(x)
    if not self.platformLeft or not self.platformRight then
        return x
    end
    
    return math.max(self.platformLeft, math.min(self.platformRight, x))
end

-- 计算到玩家的距离
function EnemyAI:getDistanceToPlayer()
    if not self.playerEntity then return math.huge end
    
    local enemyPos = self.enemyData.position
    local playerPos = self.playerEntity.position
    
    return math.sqrt(
        (playerPos.x - enemyPos.x) ^ 2 + 
        (playerPos.y - enemyPos.y) ^ 2
    )
end

-- 更新AI
function EnemyAI:update(dt, actionSystem)
    if not self.enemyData.isAlive then return end
    
    self.aiTimer = self.aiTimer + dt
    self.frameCount = self.frameCount + 1
    
    -- 更新冷却时间
    if self.attackCooldown > 0 then
        self.attackCooldown = math.max(0, self.attackCooldown - dt)
    end
    
    if self.dashCooldown > 0 then
        self.dashCooldown = math.max(0, self.dashCooldown - dt)
    end
    
    if self.bossJumpCooldown > 0 then
        self.bossJumpCooldown = math.max(0, self.bossJumpCooldown - dt)
    end
    
    if self.arrowCooldown > 0 then
        self.arrowCooldown = math.max(0, self.arrowCooldown - dt)
    end
    
    -- 更新空闲计时器
    if self.state == "idle" or self.state == "patrol" then
        self.idleTimer = self.idleTimer + dt
        if self.idleTimer > self.maxIdleTime then
            self.idleTimer = 0
            self.state = "patrol"
            self.patrolDirection = self.patrolDirection * -1  -- 改变方向
        end
    else
        self.idleTimer = 0
    end
    
    -- 缩短决策间隔，提升响应速度
    if self.aiTimer >= self.decisionInterval then
        self.aiTimer = 0
        
        -- AI决策逻辑
        if self:canSeePlayer() then
            -- 发现玩家，提高攻击性
            self.aggressionLevel = math.min(2.0, self.aggressionLevel + 0.1)
            
            if self:isPlayerInAttackRange() then
                -- 玩家在攻击范围内
                self.state = "attack"
                self:handleAttack(actionSystem)
            else
                -- 玩家不在攻击范围内，追击
                self.state = "chase"
                self:handleChase()
            end
        else
            -- 未发现玩家
            if self.state == "chase" or self.state == "attack" then
                -- 丢失目标，返回巡逻
                self.state = "patrol"
                self.aggressionLevel = math.max(1.0, self.aggressionLevel - 0.05)
            end
            
            if self.state == "idle" or self.state == "patrol" then
                self:handlePatrol()
            end
        end
        
        -- 更新敌人移动输入
        self:updateMovementInput()
    end
    
    -- 每帧都更新移动输入（保持移动流畅）
    self:updateMovementInput()
end

-- 处理巡逻状态
function EnemyAI:handlePatrol()
    if self.state == "idle" then
        -- 空闲时不移动
        self.enemyData.moveInput = 0
        
        -- 30%概率开始巡逻
        if math.random() < 0.3 then
            self.state = "patrol"
            self.patrolDirection = math.random() > 0.5 and 1 or -1
        end
    else
        -- 巡逻：来回走动
        self.enemyData.moveInput = self.patrolDirection
        
        -- 到达边界时转向
        local currentX = self.enemyData.position.x
        local targetBoundary = self.patrolDirection > 0 and self.platformRight or self.platformLeft
        
        if self.patrolDirection > 0 and currentX >= targetBoundary - 10 then
            self.patrolDirection = -1
            self.enemyData.moveInput = -1
        elseif self.patrolDirection < 0 and currentX <= targetBoundary + 10 then
            self.patrolDirection = 1
            self.enemyData.moveInput = 1
        end
    end
end

-- 处理追击状态
function EnemyAI:handleChase()
    if not self.playerEntity then return end
    
    local enemyPos = self.enemyData.position
    local playerPos = self:predictPlayerPosition()
    
    -- 决定移动方向
    local direction = 0
    if playerPos.x > enemyPos.x + 20 then
        direction = 1  -- 向右移动
    elseif playerPos.x < enemyPos.x - 20 then
        direction = -1  -- 向左移动
    end
    
    -- 限制在平台范围内
    local targetX = enemyPos.x + direction * 50
    targetX = self:clampToPlatform(targetX)
    
    -- 如果到达平台边界，尝试跳跃（如果支持）或改变策略
    if math.abs(targetX - enemyPos.x) < 10 then
        direction = -direction
    end
    
    self.enemyData.moveInput = direction * self.aggressionLevel  -- 攻击性影响移动速度
    self.enemyData.facingDirection = direction ~= 0 and direction or self.enemyData.facingDirection
    
    -- 特定敌人逻辑
    if self.enemyType == "sword" then
        -- 剑士：如果玩家在同一平台且距离较远，考虑冲锋
        local distanceX = math.abs(playerPos.x - enemyPos.x)
        if distanceX > 300 and distanceX < 600 and 
           self:isPlayerOnSamePlatform() and 
           self.dashCooldown <= 0 then
            self.isDashing = true
            self.dashCooldown = 4.0  -- 冲锋冷却4秒
            self.dashDistance = distanceX
        end
    elseif self.enemyType == "broadsword" then
        -- 刀兵：接近玩家时举刀
        local distanceX = math.abs(playerPos.x - enemyPos.x)
        if distanceX < 250 and not self.isCharging then
            self.isCharging = true
        end
    elseif self.enemyType == "archer" then
        -- 弓箭手：边后退边射击
        if self.arrowCooldown <= 0 and distanceX < 300 then
            -- 后退并射击
            self.enemyData.moveInput = -direction * 0.5
        end
    end
end

-- 处理攻击状态
function EnemyAI:handleAttack(actionSystem)
    if not actionSystem or not self.playerEntity then return end
    
    -- 停止移动
    self.enemyData.moveInput = 0
    
    -- 冷却检查
    if self.attackCooldown > 0 then
        return
    end
    
    local enemyPos = self.enemyData.position
    local playerPos = self:predictPlayerPosition()
    
    -- 设置面向玩家的方向
    local facingRight = playerPos.x > enemyPos.x
    self.enemyData.facingDirection = facingRight and 1 or -1
    if actionSystem then
        actionSystem:setFacingDirection(facingRight)
    end
    
    -- 攻击频率控制
    local currentTime = os.time()
    if currentTime - self.lastAttackTime < 1.0 / self.attackFrequency then
        return
    end
    
    self.lastAttackTime = currentTime
    
    -- 不同类型敌人的攻击逻辑
    local success = false
    
    if self.enemyType == "sword" then
        if self.isDashing then
            -- 剑士冲锋攻击
            success = actionSystem:startDash()
            self.isDashing = false
            if success then
                self.attackCooldown = self.attackCooldownTime.sword * 0.5  -- 冲锋冷却较短
            end
        else
            -- 普通攻击
            success = actionSystem:playAttackAnimation("chop")
            if success then
                self.attackCooldown = self.attackCooldownTime.sword
            end
        end
        
    elseif self.enemyType == "archer" then
        -- 弓箭手射击
        success = actionSystem:playAttackAnimation("shoot")
        if success then
            self.attackCooldown = self.attackCooldownTime.archer
            self.arrowCooldown = 0.5  -- 箭矢冷却
        end
        
    elseif self.enemyType == "broadsword" then
        -- 刀兵攻击
        if self.isCharging then
            -- 举刀靠近
            self.enemyData.moveInput = self.enemyData.facingDirection * 0.8
            success = actionSystem:playAttackAnimation("a1")
            if success then
                self.isCharging = false
                self.attackCooldown = self.attackCooldownTime.broadsword * 0.7
            end
        else
            -- 随机选择普通攻击或连斩
            if math.random() > 0.6 then  -- 40%概率使用连斩
                self.isSkillCombo = true
                success = actionSystem:playAttackAnimation("a1")
                if success then
                    self.attackCooldown = self.attackCooldownTime.broadsword * 1.2
                end
            else
                success = actionSystem:playAttackAnimation("a2")
                if success then
                    self.attackCooldown = self.attackCooldownTime.broadsword
                end
            end
        end
        
    elseif self.enemyType == "boss" then
        -- Boss攻击
        local distanceX = math.abs(playerPos.x - enemyPos.x)
        
        if distanceX > 200 and self.bossJumpCooldown <= 0 then
            -- 距离较远，使用跳劈
            success = actionSystem:startBossJumpAttack()
            if success then
                self.isBossJumpAttacking = true
                self.bossJumpCooldown = 8.0
                self.attackCooldown = self.attackCooldownTime.boss * 2
            end
        elseif distanceX > 100 then
            -- 中距离，使用冲锋
            success = actionSystem:playAttackAnimation("dash1")
            if success then
                self.attackCooldown = self.attackCooldownTime.boss
            end
        else
            -- 近距离，随机选择下劈或上挑
            if math.random() > 0.5 then
                success = actionSystem:playAttackAnimation("a1")
            else
                success = actionSystem:playAttackAnimation("a2")
            end
            if success then
                self.attackCooldown = self.attackCooldownTime.boss
            end
        end
    end
    
    if success and self.debugMode then
        print(string.format("敌人 %s 发起攻击，冷却: %.2f秒", 
            self.enemyType, self.attackCooldown))
    end

		 -- 如果攻击成功，注册攻击区域
    if success and self.combatDamageSystem then
        local enemyPos = self.enemyData.position
        local facingRight = self.enemyData.facingDirection == 1
        
        self.combatDamageSystem:registerEnemyAttack(
            self.enemyData.id,
            self.enemyType,
            enemyPos,
            facingRight
        )
    end

end

-- 更新移动输入到敌人移动系统
function EnemyAI:updateMovementInput()
    if self.enemyMovementSystem and self.enemyData.id then
        self.enemyMovementSystem:setMoveInput(
            self.enemyData.id, 
            self.enemyData.moveInput
        )
    end
end

-- 应用伤害
function EnemyAI:applyDamage(damage, actionSystem)
    if not self.enemyData.isAlive then return false end
    
    self.enemyData.health = math.max(0, self.enemyData.health - damage)
    
    if self.enemyData.health <= 0 then
        self.enemyData.isAlive = false
        return true
    end
    
    -- 播放受伤动画
    if actionSystem then
        actionSystem:playHurtAnimation()
    end
    
    -- 短暂击退效果
    if self.playerEntity and self.enemyMovementSystem then
        local direction = self.playerEntity.position.x > self.enemyData.position.x and -1 or 1
        self.enemyMovementSystem:applyImpulse(
            self.enemyData.id, 
            direction * 150 * self.aggressionLevel,  -- 攻击性影响击退力度
            80
        )
    end
    
    -- 受伤后提高攻击性
    self.aggressionLevel = math.min(2.5, self.aggressionLevel + 0.3)
    
    return false
end

-- 获取AI状态
function EnemyAI:getState()
    return {
        state = self.state,
        attackCooldown = self.attackCooldown,
        canSeePlayer = self:canSeePlayer(),
        playerInAttackRange = self:isPlayerInAttackRange(),
        distanceToPlayer = self:getDistanceToPlayer(),
        aggressionLevel = self.aggressionLevel,
        platformLeft = self.platformLeft,
        platformRight = self.platformRight,
        isDashing = self.isDashing,
        isCharging = self.isCharging,
        isSkillCombo = self.isSkillCombo
    }
end

return EnemyAI